<?php
declare (strict_types = 1);

namespace app\api\controller;
use app\model\CourseModel;
use app\model\CoursesReviewsModel;
use app\model\CoursesUsersLikeModel;
use app\model\UserModel;
use think\App;
use think\facade\Db;

class CoursesUsersLike extends Base {

    private $userModel;

    private $req;

    private $uid;

    private $coursesUsersLikeModel;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->coursesUsersLikeModel = new CoursesUsersLikeModel();

        $this->coursesReviewsModel = new CoursesReviewsModel();

        $this->uid = $this->isLogin();
    }


    /*
     * 商品评价
     *
     * */
    public function isLike(){

        if(!$this->req["course_review_id"]){
            return $this->fail("请选择要点赞的评价");
        }

        $where =[];
        $where[] = ['course_review_id','=',$this->req["course_review_id"]];
        $where[] = ['uid','=',$this->uid];

        $isLike = $this->coursesUsersLikeModel->getTotal($where);
        Db::startTrans();
        if($isLike){
            //取消点赞
            $likeRes = $this->coursesUsersLikeModel->where($where)->delete();
            $reviewRes = $this->coursesReviewsModel->where([
                'course_review_id' => $this->req["course_review_id"],
            ])->dec("like_num",1)->update();

            if($likeRes && $reviewRes){
                Db::commit();
                $this->coursesUsersLikeModel->cacelLike($this->req["course_review_id"],$this->uid);
                return $this->succ("取消点赞");
            }else{
                Db::rollback();
                return $this->fail("取消点赞失败");
            }

        }else{
            $likeRes = $this->coursesUsersLikeModel->insertGetId([
                "uid"=>$this->uid,
                "course_review_id"=>$this->req["course_review_id"]
            ]);

            $reviewRes = $this->coursesReviewsModel->where([
                'course_review_id' => $this->req["course_review_id"],
            ])->inc("like_num",1)->update();
            if($likeRes && $reviewRes){
                Db::commit();
                $this->coursesUsersLikeModel->doLike($this->req["course_review_id"],$this->uid);
                return $this->succ("点赞成功");
            }else{
                Db::rollback();
                return $this->fail("点赞失败");
            }
        }
    }
}
